// components/screen-region/screen-region.js
import {getRegions, reverseGeocoder} from "../../../../utils/Location";
import {getStorageSync} from "../../../../utils/Storage";
import {authorization} from "../../../../utils/Util";
import {getLocation} from "../../../../utils/Wx";
import CustomError from "../../../../utils/CustomError";

Component({
    /*
    * 接收外部样式
    * */
    options: {
        addGlobalClass: true,
        multipleSlots: true
    },

    /**
     * 组件的属性列表
     */
    properties: {
        show: {
            type: Boolean,
            value: false
        },
        region: {
            type: String,
            value: ""  //城市区域
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _show: false, //是否显示组件
        _active: 0,  //当前选中的组件
        _tabs: [{  //tabs栏目数
            default: "省份",
            value: "",
            current: ""
        },{
            default: "城市",
            value: "",
            current: ""
        },{
            default: "区/县",
            value: "",
            current: ""
        }],
        _list: [] //数据列表
    },

    ready: function () {

    },

    /*
    * 属性监听
    * */
    observers: {
        show: function (val) {
            if (val) {
                this._regions = [];
                this._currentRegions = [];
                this.init()
            }
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        init: async function () {
            try {
                const that = this;
                let storageRegions = getStorageSync("regions");
                that.triggerEvent("screenRegion", {name: "loading", result: {}}, {});
                let res = await this._getLocationDetail();
                if (res) { //获取定位信息
                    that.data.region = res.region;
                    that.triggerEvent("screenRegion", {name: "success", result: {
                            value: res.region,
                            current: res.district
                        }}, {});
                } else { //选择城市服务
                    !storageRegions ? storageRegions = await getRegions() : null;
                    that._regions = storageRegions;
                    that.triggerEvent("screenRegion", {name: "success", result: {}}, {});
                    let currentData = that._getCurrentData(that.data.region);
                    that.setData({
                        _show: true,
                        _tabs: currentData.tabs,
                        _list: currentData.list,
                    }, function () {
                        setTimeout(function () {
                            that.setData({
                                _active: currentData.active
                            })
                        }, 300)
                    })
                }
            } catch (e) {
                console.error(new CustomError(e, "components-select-regions2"))
            }
        },

        /*
        * 获取区域详情
        * */
        _getLocationDetail: function () {
            const that = this;
            return new Promise(async function (resolve) {
                if (!that.data.region) { //区域不存在
                    let locationDetail = getStorageSync("config.locationDetail");
                    if (locationDetail) {
                        resolve(locationDetail)
                    } else if (await authorization("scope.userLocation")) {
                        let location = await getLocation();
                        let res = await reverseGeocoder(location);
                        resolve(res);
                    }
                } else {
                    resolve(false)
                }
            }).then(function (res) {
                return res
            })
        },

        /*
        * 获取当前熟内容
        * */
        _getCurrentData: function (currentRegion) {
            let tabs = this.data._tabs;
            let regionArr = currentRegion.split(",");
            let list = [];
            let single = [], current = 0, cidx = [], firstFullName = "";
            let regions = this._regions;
            for (let i = 0; i < regionArr.length; i ++) {
                if (i === 0) {
                    single = regions[0];
                    current = single.findIndex(function (item) {
                        return item.fullname === regionArr[0]
                    });
                    firstFullName = single[current].fullname;
                    list.push(single);
                } else {
                    if (firstFullName.indexOf("市") !== -1) { //直辖市没有三级地址
                        if (i < tabs.length - 1) {
                            single = [regions[i - 1][current]];
                            current = 0;
                            list.push(single);
                        } else {
                            cidx = single[current].cidx;
                            if (cidx && cidx.length > 0) {
                                single = regions[i - 1].slice(cidx[0], cidx[1] + 1);
                                current = single.findIndex(function (item) {
                                    return item.fullname === regionArr[i]
                                });
                                list.push(single);
                            }
                        }
                    } else {
                        cidx = single[current].cidx;
                        if (cidx && cidx.length > 0) {
                            single = regions[i].slice(cidx[0], cidx[1] + 1);
                            current = single.findIndex(function (item) {
                                return item.fullname === regionArr[i]
                            });
                            list.push(single);
                        }
                    }
                }
                tabs[i].value = regionArr[i];
                tabs[i].current = current;
            }
            if (list.length < tabs.length) { // 延伸项，如果不是最后一项 则添加下一项提示
                let prevCurrent = tabs[list.length - 1].current;
                let prev = list[list.length - 1][prevCurrent];
                if (firstFullName.indexOf("市") !== -1) {
                    if (list.length + 1 === tabs.length) { //是最后一个
                        single = regions[1].slice(prev.cidx[0], prev.cidx[1] + 1);
                    } else {
                        single = [prev];
                    }
                } else {
                    single = regions[list.length].slice(prev.cidx[0], prev.cidx[1] + 1);
                }
                list.push(single)
            }
            let active = tabs.findIndex(function (item) {
                return !item.value
            }) - 1;
            return {
                tabs,
                list,
                active: active >= 0 ? active : tabs.length - 1
            }
        },

        /*
        * tabs切换
        * */
        onTabsClick: function (e) {
            let tabs = this.data._tabs;
            let currentInx = e.detail.index;
            let currentRegions = this._getSelectToString(tabs, currentInx);
            let currentData = this._getCurrentData(currentRegions);
            this.setData({
                _tabs: currentData.tabs,
                _list: currentData.list,
                _active: currentData.active
            })
        },

        /*
        * 点击栏目
        * */
        bindClickItem: function (e) {
            let tabs = this.data._tabs;
            let index = e.currentTarget.dataset.index;
            let cInx = e.currentTarget.dataset.cinx;
            let name = e.currentTarget.dataset.name;
            if (tabs[index].current !== cInx) {
                tabs[index].current = cInx;
                tabs[index].value = name;
            }
            let currentRegions =  this._getSelectToString(tabs, index);
            let currentData = this._getCurrentData(currentRegions);
            this.setData({
                _tabs: currentData.tabs,
                _list: currentData.list,
                _active: currentData.active
            })
        },


        /*
        * 获取字符串
        * */
        _getSelectToString: function (tabs, currentIndex) {
            let currentRegions = "";
            tabs = tabs.map(function (item, index) {
                if (index > currentIndex) {
                    item.value = "";
                    item.current = "";
                }
                return item
            })
            for (let i in tabs) {
                if (tabs[i].value) {
                    if (i == 0) {
                        currentRegions = tabs[i].value;
                    } else {
                        currentRegions = (currentRegions + "," + tabs[i].value)
                    }
                } else {
                    break
                }
            }
            return currentRegions
        },

        onPopClose: function () {
            this.setData({_show: false})
        },

        /*
        * 点击确定
        * */
        bindConfirm: function () {
            let tabs = this.data._tabs;
            let currentRegions = "";
            for (let i in tabs) {
                if (tabs[i].value) {
                    if (i == 0) {
                        currentRegions = tabs[i].value;
                    } else {
                        currentRegions = (currentRegions + "," + tabs[i].value)
                    }
                } else {
                    break
                }
            }
            this.setData({_show: false})
            if (currentRegions !== this.data.region) {
                let arr = currentRegions.split(",");
                this.triggerEvent("screenRegion", {
                    name: "success",
                    result: {
                        value: currentRegions,
                        current: arr[arr.length - 1]
                    }
                }, {});
            }
        }
    }
})
